package com.java.demo.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.java.demo.publics.enums.DateEnum;

/**
 * 时间工具类
 *
 * @author zhangwj
 */
public class TimeUtils {

    private static ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal = new ThreadLocal<>();

    /**
     * String转date
     *
     * @param date
     * @param dateEnum
     * @return
     * @throws ParseException
     */
    public static Date formatStringToDate(String date, final DateEnum dateEnum) throws ParseException {
        SimpleDateFormat dateFormat = getSimpleDateFormat(dateEnum);
        return dateFormat.parse(date);
    }

    /**
     * date转String
     *
     * @param date
     * @param dateEnum
     * @return
     */
    public static String formatDateToString(Date date, final DateEnum dateEnum) {
        SimpleDateFormat dateFormat = getSimpleDateFormat(dateEnum);
        return dateFormat.format(date);
    }

    /**
     * 获取线程安全的SimpleDateFormat
     *
     * @param dateEnum
     * @return
     */
    private static SimpleDateFormat getSimpleDateFormat(final DateEnum dateEnum) {
        SimpleDateFormat simpleDateFormat = simpleDateFormatThreadLocal.get();
        if (simpleDateFormat == null) {
            simpleDateFormat = new SimpleDateFormat(dateEnum.getDateType());
            simpleDateFormatThreadLocal.set(simpleDateFormat);
        }
        return simpleDateFormat;
    }

    /**
     * 根据出生日期获取年龄
     *
     * @param birthday
     * @return -1表示出生日期大于当前时间
     */
    public static int getAge(Date birthday) {
        Calendar calendar = Calendar.getInstance();
        if (calendar.before(birthday)) {
            return -1;
        }
        int yearNow = calendar.get(Calendar.YEAR);
        int monthNow = calendar.get(Calendar.MONTH);
        int dayOfMonthNow = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.setTime(birthday);

        int yearBirth = calendar.get(Calendar.YEAR);
        int monthBirth = calendar.get(Calendar.MONTH);
        int dayOfMonthBirth = calendar.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth)
                    age--;
            } else {
                age--;
            }
        }
        return age;
    }

    public static void main(String[] args) {
        try {
            Date date = new Date();
            int age = getAge(date);
            System.out.println(age);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}